package com.ycsj.goldmedalnewconcept.teacher.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.Res;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherAddStudentActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherClassInfoActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherEditTeamActivity;
import com.ycsj.goldmedalnewconcept.teacher.bean.Group;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.TeamPassData;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 展示班级学生列表的适配器
 * Created by Administrator on 2019/3/26 0026.
 */

public class RvClassInfoAdapter extends BaseQuickAdapter<Group, BaseViewHolder> {

    private Context context;

    private Activity activity;

    //展示未分组的学生的PopUpWindow相关控件
    private View view;
    private RelativeLayout rlLoading;
    private ListView lv;
    private List<StudentInfo> noTeamDatas;
    private StudentLvAdapter lvAdapter;
    private PopupWindow window;

    //定义上传给服务器的角色,对应智勇欢爱
    private String role;

    //点击位置的teamID,teamNum,classNum
    private String teamID, teamNum, classNum;

    //小组头像的集合
    private int[] res = {R.drawable.teacher_team1, R.drawable.teacher_team2, R.drawable.teacher_team3, R.drawable.teacher_team4, R.drawable.teacher_team5,
            R.drawable.teacher_team6, R.drawable.teacher_team7, R.drawable.teacher_team8, R.drawable.teacher_team9, R.drawable.teacher_team10,};


    //需要传递的小组的数据对象
    private TeamPassData teamPassData;

    //数据源
    private List<Group> data;

    //Handler
    private android.os.Handler handler = new android.os.Handler();

    public RvClassInfoAdapter(Context context, int layoutResId, @Nullable List<Group> data) {
        super(layoutResId, data);
        this.context = context;
        this.activity = (Activity) context;
        this.data = data;
    }

    @Override
    protected void convert(BaseViewHolder helper, final Group item) {
        //包含小组头像和姓名的线性布局,点击后跳转到标记
        LinearLayout llTeam = helper.getView(R.id.ll_team);
        llTeam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取小组以中已经使用的各种信息
                initPassTeamData();
                //跳转到编辑小组的界面
                Intent intent = new Intent(context, TeacherEditTeamActivity.class);
                intent.putExtra("teaminfo", item);
                //携带小组对象包含的名称,口号,目标,音乐等信息
                intent.putExtra("teampassdata", teamPassData);
                context.startActivity(intent);
            }
        });

        //小组头像
        RoundedImageView ivTeam = helper.getView(R.id.iv_team_img);
        ivTeam.setImageResource(res[item.icon - 1]);


        //小组姓名
        TextView tvTeamName = helper.getView(R.id.tv_team_name);
        if (TextUtils.isEmpty(item.name)) {
            tvTeamName.setText("暂无");
        } else {
            tvTeamName.setText(item.name);
        }

        //展示小组成员的GridView
        MyGridView mGv = helper.getView(R.id.mgv);
        //小组的默认四个成员
        List<StudentInfo> persons = item.persons;
        final TeamGvAdapter teamGvAdapter = new TeamGvAdapter(activity, context, persons, R.layout.teacher_gv_student);
        mGv.setAdapter(teamGvAdapter);

        //点击事件的回调
        teamGvAdapter.setOnOutClickListener(new TeamGvAdapter.OnOutClickListener() {
            @Override
            public void onOUtclick(int pos, StudentInfo info) {

                //根据当前位置的学生是否学生,如果有学生
                if (TextUtils.isEmpty(info.getName())) {
                    //判断标准根据当前位置的学生姓名来判断,无学生,弹出右边的展示未分组的学生列表面板

                    //记录点击位置的用户角色
                    switch (pos) {
                        case 0:
                            role = "wisdom";
                            break;
                        case 1:
                            role = "brave";
                            break;
                        case 2:
                            role = "joy";
                            break;
                        case 3:
                            role = "love";
                            break;
                    }

                    //记录点击位置的teamId,teamNum,classNum
                    teamID = info.getTeamId();
                    teamNum = info.getTeamnum() + "";
                    classNum = info.getClassnum() + "";
                    //弹出未分组的学生面板
                    showNoTeamPop();
                } else {
                    //有学生,跳转到修改学生的界面
                    Intent intent = new Intent(context, TeacherAddStudentActivity.class);
                    intent.putExtra("studentinfo", info);
                    context.startActivity(intent);
                }
            }
        });

        //长按事件的回调
        teamGvAdapter.setOnOutLongClickListener(new TeamGvAdapter.OnOutLongClickListener() {
            @Override
            public void onLongClick(int pos, final StudentInfo person) {
                person.isDelete = true;
                teamGvAdapter.notifyDataSetChanged();

                PopUpManager.showPop(context, R.layout.teacher_pop_clean_cach, 0.3f, activity, new PopUpManager.onGetViewListener() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                        ImageView ivClose = view.findViewById(R.id.lv_close);
                        //文本提示信息
                        TextView tvMsg = view.findViewById(R.id.tv_message);
                        tvMsg.setText("确定移除该学生吗?");
                        Button btCommit = view.findViewById(R.id.bt_commit);
                        ivClose.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //关闭弹框
                                PopUpManager.dismiss();
                                //状态
                                person.isDelete = false;
                                notifyDataSetChanged();
                            }
                        });
                        btCommit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //请求服务器删除该位置的学生
                                httpDeleteSudent(person);
                            }
                        });
                    }
                }, new PopUpManager.onDismissListener() {
                    @Override
                    public void onDismiss() {
                        //消失的监听
                        if (person.isDelete != false) {
                            person.isDelete = false;
                            notifyDataSetChanged();
                        }
                    }
                });
            }
        });
    }


    /**
     * 请求服务器删除该位置学生的方法
     *
     * @param item
     */
    private void httpDeleteSudent(final StudentInfo item) {

        PopUpManager.dismiss();

        CustomDialogManager.show(context, "移除中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "11");
        map.put("teamID", item.teamId);
        map.put("studentID", item.id + "");
        map.put("studentTel", item.tel);

        HttpUtils.post(HttpAddress.MOVESTUDENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort(BaseApplication.ERROR);
                CustomDialogManager.dissmiss();
                if (item.isDelete != false) {
                    item.isDelete = false;
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onResponse(String response, int id) {

                if (!TextUtils.isEmpty(response)) {
                    Res info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, Res.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if (1 == info.getState()) {
                            //返回成功
                            //通知页面刷新
                            BusInfo busInfo = new BusInfo();
                            busInfo.type = TeacherClassInfoActivity.CREATEGROUPSUCCESS;
                            EventBus.getDefault().post(busInfo);
                            //延时关闭弹框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    CustomDialogManager.dissmiss();
                                    ToastUtils.showShort("移除成功");
                                }
                            }, 800);

                        } else {
                            CustomDialogManager.dissmiss();
                            ToastUtils.showShort("移除失败,返回错误码:" + info.getState());
                            Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                        }
                    }

                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }


    /**
     * 展示未分组的学生面板
     */
    private void showNoTeamPop() {

        view = View.inflate(context, R.layout.teacher_noteam_student, null);

        //加载视图
        rlLoading = view.findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);

        //展示学生列表的数据
        lv = view.findViewById(R.id.lv);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int currpos, long l) {
                //同步展示未分组学生的列表状态
                AddStudentToTeam(noTeamDatas.get(currpos));
            }
        });

        //设置ListView的数据
        window = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        UiUtils.backgroundAlpha(activity, 0.8f);
        window.setAnimationStyle(R.style.AnimationRightFade);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                UiUtils.backgroundAlpha(activity, 1.0f);
            }
        });

        window.showAtLocation(activity.getLayoutInflater().inflate(R.layout.activity_teacher_classinfo, null), Gravity.RIGHT, 0, 0);

        //请求未分组的学生信息
        Map<String, String> map = new HashMap<>();
        map.put("type", "10");
        map.put("userID", AccountUtils.getAccount(context));

        HttpUtils.post(HttpAddress.NOTEAM, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    if (null != rlLoading) {
                        rlLoading.setVisibility(View.GONE);
                    }
                    //创建未分组学生的集合
                    noTeamDatas = new ArrayList<>();
                    try {
                        //解析服务器返回的数据
                        JSONObject stu = new JSONObject(response);
                        int size = stu.getInt("size");
                        for (int i = 0; i < size; i++) {
                            JSONObject object = stu.getJSONObject("student" + i);
                            StudentInfo info = new StudentInfo();
                            info.setBirthday(object.getString("birthday"));
                            info.setAddress(object.getString("address"));
                            info.setGender(object.getString("gender"));
                            info.setIcon(object.getString("icon"));
                            info.setClassnum(object.getInt("classnum"));
                            info.setUserID(object.getString("userID"));
                            info.setMoney(object.getInt("money"));
                            info.setSchool(object.getString("school"));
                            info.setGrade(object.getString("grade"));
                            info.setName(object.getString("name"));
                            info.setNickname(object.getString("nickname"));
                            info.setTel(object.getString("tel"));
                            info.setPayment(object.getString("payment"));
                            info.setId(object.getInt("id"));
                            info.setExp(object.getInt("exp"));
                            info.setFavorite(object.getString("favorite"));
                            info.setTeamnum(object.getInt("teamnum"));
                            noTeamDatas.add(info);
                        }

                        lvAdapter = new StudentLvAdapter(context, noTeamDatas, R.layout.teacher_lv_student);
                        lv.setAdapter(lvAdapter);
                    } catch (Exception e) {
                        Log.i("test", e.toString());
                    }
                }
            }
        });
    }

    /**
     * 请求服务器添加进学生进小组
     *
     * @param studentAdd 被添加的位置的学生对象
     */
    private void AddStudentToTeam(StudentInfo studentAdd) {

        //关闭右侧弹框
        if (window != null && window.isShowing()) {
            window.dismiss();
            window = null;
            view = null;
        }

        CustomDialogManager.show(context, "添加中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "12");
        map.put("studentID", studentAdd.getId() + "");//未分组学生的ID
        map.put("studentTel", studentAdd.getTel() + "");//未分组学生的电话
        map.put("teamID", teamID);//需要添加学生位置的teamID
        map.put("teamnum", teamNum);//需要添加学生位置的teamNum
        map.put("classnum", classNum);//需要添加学生位置的classNum
        map.put("role", role);//需要添加学生位置的用户角色,对应智勇欢爱,点击的时候记录

        HttpUtils.post(HttpAddress.ADDSTUDENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort(BaseApplication.ERROR);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    Res info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, Res.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if (1 == info.getState()) {
                            //返回成功
                            BusInfo busInfo = new BusInfo();
                            busInfo.type = TeacherClassInfoActivity.CREATEGROUPSUCCESS;
                            EventBus.getDefault().post(busInfo);
                            //延时取消加载框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    CustomDialogManager.dissmiss();

                                    ToastUtils.showShort("添加成功");
                                }
                            }, 800);

                        } else {
                            CustomDialogManager.dissmiss();
                            ToastUtils.showShort("添加失败,返回错误码:" + info.getState());
                            Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                        }
                    }


                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }


    /**
     * 跳转的时候获取封装小组各信息的对象
     */
    private void initPassTeamData() {
        teamPassData = new TeamPassData();
        List<String> teamNames = new ArrayList<>();
        List<String> teamSlogans = new ArrayList<>();
        List<String> teamAims = new ArrayList<>();
        List<String> teamMusics = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            teamNames.add(data.get(i).name);
            teamSlogans.add(data.get(i).slogan);
            teamAims.add(data.get(i).taget);
            teamMusics.add(data.get(i).music);
        }
        teamPassData.teamNames = teamNames;
        teamPassData.teamSlogans = teamSlogans;
        teamPassData.teamAims = teamAims;
        teamPassData.teamMusics = teamMusics;
    }

}
